<template>
  <div class="home container">
    <alert v-if="alert" :messages="alert"/>
    <h1 class="page-header">用户管理系统</h1>
    <div class="row">
      <div class="col-xs-10">
        <input type="search" class="form-control" placeholder="搜索" v-model="searchInput"/>
      </div>
      <!--<div class="col-xs-2">-->
        <!--<button type="button" class="btn btn-success" @click="clickSeach()">搜索</button>-->
      <!--</div>-->
    </div>

    <table class="table table-striped">
      <thead>
        <tr>
          <th>姓名</th>
          <th>电话</th>
          <th>邮箱</th>
          <th></th>
        </tr>
      </thead>
      <tbody><!--filterBy 触发的方法-->
        <tr v-for="(customer, index) of filterBy(customers, searchInput)" :key="index">
          <td>{{customer.name}}</td>
          <td>{{customer.phone}}</td>
          <td>{{customer.email}}</td>
          <td><router-link class="btn btn-default" :to="'/details/' + customer.id">详情</router-link></td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<script>

import Alert from './components/Alert'
export default {
  name: 'home',
  components: {
    Alert
  },
  data () {
    return {
      customers: [],
      alert: '',
      searchInput: ''
    }
  },
  created () {
    if (this.$route.query.alert) {
      this.alert = this.$route.query.alert
      let that = this
      setTimeout(() => {
        that.alert = false
      }, 1000)
    }
    this.getCustomer()
  },
  updated () { // data数据改变更新后执行此函数
    this.$nextTick(() => {
      this.getCustomer()
      // 在下次 DOM 更新循环结束之后执行这个回调。在修改数据之后立即使用这个方法，获取更新后的DOM.
    })
  },
  methods: {
    getCustomer () {
      this.axios.get('/users')
        .then((res) => {
          const data = res.data
          console.log(data)
          this.customers = data
        })
    },
    filterBy (customers, val) { // 遍历数组，并判断是否有这个值
      return customers.filter((customer) => {
        return (customer.name.match(val) || customer.phone.match(val)) // match() 方法可在字符串内检索指定的值，或找到一个或多个正则表达式的匹配。
      })
    }
  }
}
</script>

<style lang="stylus" scoped>

</style>
